#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>
#include <QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 实例化socket
    socket = new QUdpSocket(this);

    this->setWindowTitle("服务端");

    // 连接信号槽
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processRequest);

    // 绑定端口
    bool ret = socket->bind(QHostAddress::Any,8080);
    if(!ret)
    {
        // 弹出错误对话框
        QMessageBox::critical(this,"服务器绑定出错",socket->errorString());
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::processRequest()
{
    // 读取请求
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram();
    // 转换成字符串
    const QString& request = requestDatagram.data();
    // 响应
    const QString response = process(request);
    // 响应写回客服端
    QNetworkDatagram responseDatagram(response.toUtf8(),requestDatagram.senderAddress(),requestDatagram.senderPort());
    socket->writeDatagram(responseDatagram);

    // 显示打印日志
    // 显示打印日志
    QString log = "[" + requestDatagram.senderAddress().toString() + ":" +
                  QString::number(requestDatagram.senderPort())
                  + "] req: " + request + ", resp: " + response;
    ui->listWidget->addItem(log);

}

QString Widget::process(const QString &request)
{
    return request;

}
